//
//  Foudation+More.swift
//  ContactPoster
//
//  Created by TSYH on 2023/11/22.
//

import CryptoKit
import UIKit

public func Log<T>(_ messsage: T, file: String = #file, funcName: String = #function, lineNum: Int = #line) {
    #if DEBUG
    let fileName = (file as NSString).lastPathComponent
    print(Date().description + " \(fileName) (\(funcName)): [\(lineNum)]- \(messsage)")
    #endif
}

public extension Array {
    func value(at index: Int) -> Element? {
        guard index >= 0, index < count else {
            return nil
        }
        return self[index]
    }
}

public extension String {
    func RGBAValue() -> (r: CGFloat, g: CGFloat, b: CGFloat, a: CGFloat)? {
        var r:CGFloat = 0;
        var g:CGFloat = 0;
        var b:CGFloat = 0;
        var a:CGFloat = 0;
        var prefix: Int = 0;

        let color: String = trimmingCharacters(in: .whitespacesAndNewlines).uppercased()
        if (color.hasPrefix("#")) {
            prefix = 1
        }
        else if (color.hasPrefix("0X")) {
            prefix = 2
        }
        let length: Int = color.count - prefix
        //         RGB            RGBA          RRGGBB        RRGGBBAA
        
        func componentFrom(string: String, start: Int, length: Int) -> CGFloat {
            guard start >= 0, start + length <= string.count else {
                return 0
            }
            
            let begin = string.index(startIndex, offsetBy: start)
            let end = string.index(startIndex, offsetBy: start + length)
            
            let sub = string[begin..<end]
            var full = String(sub)
            if length == 1 {
                full += full
            }
            
            var hex: UInt64 = 0
            Scanner(string: full).scanHexInt64(&hex)
            
            let float = CGFloat(hex) / 255.0
            return float
        }
        
        switch length {
        case 3: // RGB
            r = componentFrom(string: color, start: prefix, length: 1)
            g = componentFrom(string: color, start: prefix + 1, length: 1)
            b = componentFrom(string: color, start: prefix + 2, length: 1)
            a = 1
        case 4: // RGBA
            r = componentFrom(string: color, start: prefix, length: 1)
            g = componentFrom(string: color, start: prefix + 1, length: 1)
            b = componentFrom(string: color, start: prefix + 2, length: 1)
            a = componentFrom(string: color, start: prefix + 3, length: 1)
        case 6: // RRGGBB
            r = componentFrom(string: color, start: prefix, length: 2)
            g = componentFrom(string: color, start: prefix + 2, length: 2)
            b = componentFrom(string: color, start: prefix + 4, length: 2)
            a = 1
        case 8: // RRGGBBAA
            r = componentFrom(string: color, start: prefix, length: 2)
            g = componentFrom(string: color, start: prefix + 2, length: 2)
            b = componentFrom(string: color, start: prefix + 4, length: 2)
            a = componentFrom(string: color, start: prefix + 6, length: 2)
        default:
            return nil
        }
        
        return (r, g, b, a)

    }
    
    var color: UIColor? {
        if let rgba = RGBAValue() {
            return UIColor(red: rgba.r, green: rgba.g, blue: rgba.b, alpha: rgba.a)
        }
        return nil
    }
    
    var md5String: String? {
        guard let data = data(using: .utf8) else {
            return nil
        }
        
        let digest = Insecure.MD5.hash(data: data)
        return digest.map {
                    String(format: "%02hhx", $0)
        }.joined()
    }
    
    var localFilePath: String {
        var path = self
        if path.lowercased().hasPrefix("file://") {
            path.removeFirst("file://".count)
        }
        return path
    }
}

public extension Error {
    var localizedFailureReason: String {
//        "The operation couldn’t be completed. (PHPhotosErrorDomain error 3072.)"
        let values = self.localizedDescription.components(separatedBy: "(")
        return values.first ?? self.localizedDescription
    }
}
